package com.htn.gateway.filter;

import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

import cn.hutool.core.collection.CollectionUtil;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.CommonConstants;
import com.htn.common.core.constant.SecurityConstants;
import com.htn.common.core.exception.CaptchaException;
import com.htn.gateway.config.properties.CaptchaProperties;
import com.htn.system.api.RemoteUserService;
import org.apache.commons.collections4.Unmodifiable;
import org.apache.commons.collections4.list.UnmodifiableList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import com.htn.common.core.utils.ServletUtils;
import com.htn.common.core.utils.StringUtils;
import com.htn.gateway.service.ValidateCodeService;
import org.springframework.util.MultiValueMap;
import org.springframework.util.MultiValueMapAdapter;
import reactor.core.publisher.Flux;

/**
 * 验证码过滤器
 * 
 * @author htn
 */
@Component
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object>
{
    private final static String[] VALIDATE_URL = new String[] { "/login", "/register" };

    @Autowired
    private ValidateCodeService validateCodeService;

    @Autowired
    private CaptchaProperties captchaProperties;

    private static final String CODE = "code";

    private static final String UUID = "uuid";

    @Override
    public GatewayFilter apply(Object config){
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            // 非登录/注册请求或验证码关闭，不处理
            if (!StringUtils.containsAnyIgnoreCase(request.getURI().getPath(), VALIDATE_URL) )
            {
                return chain.filter(exchange);
            }
            try {
                MultiValueMap<String,String> map = request.getQueryParams();
                String type = null;
                String username  = null;
                String code = null;
                if(CollectionUtil.isNotEmpty(map.get("type"))){
                    type= map.get("type").get(0);
                }
                if(CollectionUtil.isNotEmpty(map.get("username"))){
                    username= map.get("username").get(0);
                }
                if(CollectionUtil.isNotEmpty(map.get("code"))){
                    code= map.get("code").get(0);
                }
                if (StringUtils.isNotBlank(type) && type.equals(CommonConstants.UserRole.BIZ.name())) {
                    String rspStr = resolveBodyFromRequest(request);
                    JSONObject obj = JSONObject.parseObject(rspStr);
                    validateCodeService.checkCapcha(obj.getString(CODE), obj.getString(UUID));
                }
            }
            catch (Exception e)
            {
                return ServletUtils.webFluxResponseWriter(exchange.getResponse(), e.getMessage());
            }
            return chain.filter(exchange);
        };
    }

    private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest){
        // 获取请求体
        Flux<DataBuffer> body = serverHttpRequest.getBody();
        AtomicReference<String> bodyRef = new AtomicReference<>();
        body.subscribe(buffer -> {
            CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
            DataBufferUtils.release(buffer);
            bodyRef.set(charBuffer.toString());
        });
        return bodyRef.get();
    }
}
